package com.spzx.common.log.aspect;

import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.log.annotation.ExecuteStatistics;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

/*
    接口方法执行时长统计的切面类
 */
@Aspect
@Component
@Slf4j
public class ExecuteStatisticsAspect {

    //环绕通知: 切入点表达式为 自定义注解
    @Around(value = "@annotation(executeStatistics)")
    public Object around(ProceedingJoinPoint point, ExecuteStatistics executeStatistics){
        try {
//            MethodSignature signature = (MethodSignature) point.getSignature();
            long start = System.currentTimeMillis();
            //获取目标方法的参数列表
            Object[] args = point.getArgs();
            //执行被代理的目标方法 得到目标方法的返回值
            Object result = point.proceed(args);
            long time = System.currentTimeMillis() - start;
            log.info(executeStatistics.title() + " 执行的时长为："+ time+" ms");
            //返回执行结果
            return result;
        } catch (Throwable e) {
            throw new ServiceException(e.getMessage());
        }
    }
}
